package com.smartcruise.util.network;

import android.util.Log;

import com.smartcruise.util.Key;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by FengChaoQun
 * on 2018/3/26 0026
 */

public class ResultInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception var25) {
            throw var25;
        }

        ResponseBody body = response.body();
        BufferedSource source = body.source();
        source.request(9223372036854775807L);
        Buffer buffer = source.buffer();
        String s = buffer.clone().readString(Charset.forName("UTF-8"));
        try {
            JSONObject jsonObject = new JSONObject(s);
            String code = jsonObject.getString(Key.code);
            String message = jsonObject.getString(Key.message);
            Log.d("ResultInterceptor", "jsonObject:" + jsonObject);
            if (Key.expiredToken.equals(message)) {
                Log.d("ResultInterceptor", Thread.currentThread().getName());
                Log.e("ResultInterceptor", "is expired");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return response;
    }
}
